using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using Blackbird.Core.Base;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Blackbird.Core.Entities.Sprites
{
    [Serializable]
    public class GameCursor : BaseMultiframe
    {
        private Point _hotSpot;
        private Vector2 _hotspotVector;

        public Frameset Frameset { get; set; }
        public string Name { get; set; }

        public virtual Point HotSpot
        {
            get { return _hotSpot; }
            set
            {
                _hotSpot = value;
                _hotspotVector = new Vector2(_hotSpot.X, _hotSpot.Y);
            }
        }

        public override void Render(SpriteBatch spriteBatch)
        {
            Vector2 transformedLocation = Position - _hotspotVector;
            Texture2D texture = TexturePool.Instance[CurrentFrame.TextureId];
            var destination = new Rectangle((int) transformedLocation.X, (int) transformedLocation.Y,
                                            (int) (texture.Width*Scale.X),
                                            (int) (texture.Height*Scale.Y));
            spriteBatch.Draw(texture, destination, null, ModulationColor, Rotation, Origin, SpriteEffects.None, 1.0f);
        }

        #region Factory

        public static GameCursor CreateFromFile(string filename)
        {
            var stream = new FileStream(filename, FileMode.Open);
            var serializer = new XmlSerializer(typeof (GameCursor));
            XmlReader reader = XmlReader.Create(stream);
            var cursor = (GameCursor) serializer.Deserialize(reader);
            reader.Close();
            stream.Close();

            return cursor;
        }

        public static void SaveToFile(GameCursor cursor, string filename)
        {
            var stream = new FileStream(filename, FileMode.Create);
            var serializer = new XmlSerializer(typeof (GameCursor));
            XmlWriter writer = XmlWriter.Create(stream);
            serializer.Serialize(writer, cursor);
            writer.Close();
            stream.Close();
        }

        #endregion
    }
}